export default {
  namespaced: true,
  state: {
    cartData: []
  },
  mutations: {
    SET_CART(state, paylord) {
      // state.cartData = paylord

      //先检查cartData有没有这条数据（find）
      let target = state.cartData.find((item) => item.id === paylord.id)
      //没有

      if (!target) {
        //将数据添加进cartData，第一次加入数量为1，需要手动添加数量字段count
        let obj = {
          title: paylord.title,
          price: paylord.price,
          count: 1,
          id: paylord.id
        }
        state.cartData.push(obj)
      } else {
        //有
        //让count+1
        target.count++
      }
    }
  },
  actions: {
    ADD_CART(context, paylord) {
      context.commit("SET_CART", paylord)
      context.commit("product/DECREASE_INVENTORY", paylord.id, { root: true })
    }
  },
  getters: {
    total(state) {
      return state.cartData
        .reduce((total, item) => {
          return (total += item.price * item.count)
        }, 0)
        .toFixed(2)
    }
  }
}
